import cv2

red = (0, 0, 255)


# ==============================
# 轮廓绘制
# ==============================
def test1():
    #
    src = cv2.imread('graph.png')

    # 转换颜色空间
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    # 绘制轮廓，画轮廓是会直接修改原图，如果保证原图不变，建议先拷贝
    copy = src.copy()
    my_img = cv2.drawContours(copy, contours, -1, red, 2)
    #
    cv2.imshow('src', src)
    cv2.imshow('Contour1s', my_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def test2():
    #
    src = cv2.imread('test.png')

    # 转换颜色空间
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 遍历轮廓
    for i, contour in enumerate(contours):
        # 可以在这里添加代码处理每个轮廓
        my_img = cv2.drawContours(src, [contour], -1, red, 2)
        # 打印当前轮廓的索引
        print("Contour {} has {} points".format(i, len(contour)))
        # 展示图片
        cv2.imshow('Contours', my_img)
        cv2.waitKey(0)
        # cv2.destroyAllWindows()
